#!/usr/bin/env python
#coding=utf-8
import time

from flask import request, current_app


from aladin.database import db
from aladin.helpers import toint, log_debug, log_info, log_error
from aladin.ext.aliyun import AliyunOSS, UploadNotAllowed

from app.models.sys import SysCategory

class CategoryService(object):
    """类目service"""
    def __init__(self, form, cat_id, cat_type):
        self.form = form
        self.errmsg = {}
        self.cat_id = cat_id
        self.cat_type = cat_type
        self.is_new = False if self.cat_id else True
        log_debug('is_new:%s' % self.is_new)

    def save(self):
        """保存类目"""

        need_arr = ['cat_pid', 'cat_name']
        for k in need_arr:
            v = self.form.get(k)
            if not v:
                self.errmsg[k] = u'必填项'

        if self.is_new and self.cat_type == 0:
            if not request.files.get('cat_img'):
                self.errmsg['cat_img'] = u'图片是必填项'

        if self.errmsg:
            return self.errmsg

        cat = SysCategory()
        if not self.is_new:
            cat = SysCategory.query.get_or_404(self.cat_id)

        cat_pid = toint(self.form.get('cat_pid', '0'))
        cat_name = self.form.get('cat_name', '')
        cat_desc = self.form.get('cat_desc', '')

        cat.cat_pid  = cat_pid
        cat.cat_name = cat_name
        cat.cat_desc = cat_desc
        cat.cat_type = self.cat_type

        if request.files.get('cat_img'):
            oss = AliyunOSS('category', current_app.config['SAVE_TARGET_PATH'])
            try:
                oss.save(request.files['cat_img'])
                cat.cat_img = oss.put_to_oss()

            except UploadNotAllowed, e:
                return u'只允许是图片文件'
            except Exception, e:
                log_info('Exception:%s' % e)
                return u'发生错误，上传失败'

        if self.is_new:
            db.session.add(cat)

        db.session.commit()

        return {}



